<template>
  <div class="notification-center">
    <!-- 顶部标题栏 -->
    <div class="page-header">
      <el-button class="back-btn" circle @click="goHome">
        <el-icon><ArrowLeft /></el-icon>
      </el-button>
      <h1>💌 消息中心</h1>
      <div class="placeholder"></div>
    </div>

    <!-- 未读数量提示 -->
    <div class="unread-tip" v-if="unreadCount > 0">
      <el-icon><Bell /></el-icon>
      您有 <span class="count">{{ unreadCount }}</span> 条未读消息
    </div>

    <!-- 操作按钮区 -->
    <div class="action-bar" v-if="notificationList.length > 0">
      <!-- 批量选择模式下的按钮 -->
      <template v-if="batchMode">
        <el-button
          class="action-btn cancel-btn"
          @click="cancelBatchMode"
        >
          ❌ 取消
        </el-button>
        <el-button
          class="action-btn confirm-btn"
          type="success"
          @click="confirmBatchDelete"
          :disabled="selectedNotifications.length === 0"
        >
          ✅ 确认删除 ({{ selectedNotifications.length }})
        </el-button>
      </template>

      <!-- 正常模式下的按钮 -->
      <template v-else>
        <el-button
          class="action-btn"
          type="primary"
          @click="handleMarkAllAsRead"
          :disabled="unreadCount === 0"
        >
          全部标记为已读
        </el-button>
        <el-button
          class="action-btn"
          type="danger"
          plain
          @click="enterBatchMode"
        >
          🗑️ 批量删除
        </el-button>
        <el-button
          class="action-btn"
          type="warning"
          plain
          @click="handleDeleteAll"
        >
          🧹 一键清空
        </el-button>
      </template>
    </div>

    <!-- 通知列表 -->
    <div class="notification-list" v-loading="loading">
      <div
        v-for="item in notificationList"
        :key="item.id"
        class="notification-item"
        :class="{
          'unread': item.isRead === 0,
          'selected': isSelected(item.id),
          'batch-mode': batchMode
        }"
        @click="handleCardClick(item)"
      >
        <!-- 批量选择模式下显示复选框 -->
        <div v-if="batchMode" class="notification-checkbox" @click.stop="toggleSelect(item.id)">
          <el-checkbox
            :model-value="isSelected(item.id)"
            @change="toggleSelect(item.id)"
            size="large"
          />
        </div>

        <!-- 通知图标 -->
        <div class="notification-icon">
          <el-icon :size="24" :color="getIconColor(item.type)">
            <component :is="getIconComponent(item.type)" />
          </el-icon>
        </div>

        <!-- 通知内容 -->
        <div class="notification-content">
          <div class="notification-title">
            {{ item.title }}
            <el-tag v-if="item.isRead === 0" type="danger" size="small" effect="dark">未读</el-tag>
          </div>
          <div class="notification-text">{{ item.content }}</div>
          <div class="notification-time">{{ formatTime(item.createdAt) }}</div>
        </div>

        <!-- 操作按钮 -->
        <div class="notification-actions" v-if="!batchMode">
          <el-button
            v-if="item.isRead === 0"
            type="primary"
            size="small"
            text
            @click.stop="handleMarkAsRead(item.id)"
          >
            标记已读
          </el-button>
          <el-button
            type="danger"
            size="small"
            text
            @click.stop="handleDelete(item.id)"
          >
            删除
          </el-button>
        </div>
      </div>

      <!-- 空状态 -->
      <el-empty 
        v-if="!loading && notificationList.length === 0" 
        description="暂无消息"
        :image-size="120"
      />
    </div>

    <!-- 分页 -->
    <div class="pagination" v-if="total > 0">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        @current-change="loadNotifications"
        @size-change="loadNotifications"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Bell,
  Money,
  Wallet,
  TrophyBase,
  ChatDotRound,
  Calendar,
  Document,
  SuccessFilled,
  WarningFilled,
  ArrowLeft
} from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import {
  getNotificationList,
  markNotificationAsRead,
  markAllNotificationsAsRead,
  deleteNotification,
  batchDeleteNotifications,
  deleteAllNotifications,
  getUnreadCount
} from '@/api'

const router = useRouter()
const userStore = useUserStore()

// 数据
const loading = ref(false)
const notificationList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const selectedNotifications = ref([]) // 选中的通知ID列表
const batchMode = ref(false) // 批量选择模式

// 未读数量
const unreadCount = computed(() => userStore.unreadCount)

// 加载通知列表
const loadNotifications = async () => {
  loading.value = true
  try {
    const res = await getNotificationList({
      pageNum: currentPage.value,
      pageSize: pageSize.value
    })
    
    if (res.code === 200) {
      notificationList.value = res.data.records
      total.value = res.data.total
    }
  } catch (error) {
    console.error('加载通知列表失败', error)
    ElMessage.error('加载通知列表失败')
  } finally {
    loading.value = false
  }
}

// 更新未读数量
const updateUnreadCount = async () => {
  try {
    const res = await getUnreadCount()
    if (res.code === 200) {
      userStore.setUnreadCount(res.data)
    }
  } catch (error) {
    console.error('获取未读数量失败', error)
  }
}

// 标记单条为已读
const handleMarkAsRead = async (id) => {
  try {
    const res = await markNotificationAsRead(id)
    if (res.code === 200) {
      ElMessage.success('已标记为已读')
      // 更新列表
      const item = notificationList.value.find(n => n.id === id)
      if (item) {
        item.isRead = 1
      }
      // 更新未读数量
      updateUnreadCount()
    }
  } catch (error) {
    console.error('标记已读失败', error)
    ElMessage.error('标记已读失败')
  }
}

// 标记全部为已读
const handleMarkAllAsRead = async () => {
  try {
    await ElMessageBox.confirm('确定要将所有消息标记为已读吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    })

    const res = await markAllNotificationsAsRead()
    if (res.code === 200) {
      ElMessage.success('已全部标记为已读')
      // 重新加载列表
      loadNotifications()
      // 更新未读数量
      updateUnreadCount()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('标记全部已读失败', error)
      ElMessage.error('标记全部已读失败')
    }
  }
}

// 删除通知
const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这条消息吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const res = await deleteNotification(id)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      // 重新加载列表
      loadNotifications()
      // 更新未读数量
      updateUnreadCount()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除通知失败', error)
      ElMessage.error('删除失败')
    }
  }
}

// 点击卡片
const handleCardClick = (item) => {
  // 批量选择模式：点击卡片切换选中状态
  if (batchMode.value) {
    toggleSelect(item.id)
  } else {
    // 正常模式：点击通知
    handleNotificationClick(item)
  }
}

// 点击通知
const handleNotificationClick = (item) => {
  // 如果未读，先标记为已读
  if (item.isRead === 0) {
    handleMarkAsRead(item.id)
  }

  // 跳转到相关页面
  const type = item.type
  const relatedId = item.relatedId

  switch (type) {
    case 'BILL_APPROVAL':
      router.push('/bill/pending')
      break
    case 'BALANCE_REQUEST':
      router.push('/balance')
      break
    case 'TREASURY_CHANGE':
      router.push('/treasury')
      break
    case 'BILL_APPROVAL_RESULT':
      if (relatedId) {
        router.push(`/bill/detail/${relatedId}`)
      }
      break
    case 'BALANCE_APPROVAL_RESULT':
      router.push('/balance')
      break
    default:
      break
  }
}

// 判断是否选中
const isSelected = (id) => {
  return selectedNotifications.value.includes(id)
}

// 切换选中状态
const toggleSelect = (id) => {
  const index = selectedNotifications.value.indexOf(id)
  if (index > -1) {
    selectedNotifications.value.splice(index, 1)
  } else {
    selectedNotifications.value.push(id)
  }
}

// 进入批量选择模式
const enterBatchMode = () => {
  batchMode.value = true
  selectedNotifications.value = []
  ElMessage.info('请点击消息进行选择')
}

// 取消批量选择模式
const cancelBatchMode = () => {
  batchMode.value = false
  selectedNotifications.value = []
}

// 确认批量删除
const confirmBatchDelete = async () => {
  if (selectedNotifications.value.length === 0) {
    ElMessage.warning('请先选择要删除的消息')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedNotifications.value.length} 条消息吗？`,
      '批量删除',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        confirmButtonClass: 'el-button--danger'
      }
    )

    const res = await batchDeleteNotifications(selectedNotifications.value)
    if (res.code === 200) {
      ElMessage.success(`成功删除 ${selectedNotifications.value.length} 条消息`)
      selectedNotifications.value = []
      batchMode.value = false
      loadNotifications()
      updateUnreadCount()
    } else {
      ElMessage.error(res.msg || '批量删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败：', error)
      ElMessage.error('批量删除失败')
    }
  }
}

// 一键删除所有
const handleDeleteAll = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除所有消息吗？此操作不可恢复！`,
      '一键清空',
      {
        confirmButtonText: '确定清空',
        cancelButtonText: '取消',
        type: 'error',
        confirmButtonClass: 'el-button--danger'
      }
    )

    const res = await deleteAllNotifications()
    if (res.code === 200) {
      ElMessage.success('已清空所有消息')
      selectedNotifications.value = []
      loadNotifications()
      updateUnreadCount()
    } else {
      ElMessage.error(res.msg || '清空失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('清空失败：', error)
      ElMessage.error('清空失败')
    }
  }
}

// 获取图标组件
const getIconComponent = (type) => {
  const iconMap = {
    'BILL_APPROVAL': Money,
    'BALANCE_REQUEST': Wallet,
    'TREASURY_CHANGE': TrophyBase,
    'BILL_APPROVAL_RESULT': SuccessFilled,
    'BALANCE_APPROVAL_RESULT': SuccessFilled,
    'ANNIVERSARY_REMINDER': Calendar,
    'DIARY_COMMENT': ChatDotRound,
    'NOTE_RECEIVED': Document
  }
  return iconMap[type] || Bell
}

// 获取图标颜色
const getIconColor = (type) => {
  const colorMap = {
    'BILL_APPROVAL': '#ff6b9d',
    'BALANCE_REQUEST': '#ff6b9d',
    'TREASURY_CHANGE': '#ffa07a',
    'BILL_APPROVAL_RESULT': '#67c23a',
    'BALANCE_APPROVAL_RESULT': '#67c23a',
    'ANNIVERSARY_REMINDER': '#ff6b9d',
    'DIARY_COMMENT': '#409eff',
    'NOTE_RECEIVED': '#ff6b9d'
  }
  return colorMap[type] || '#909399'
}

// 返回主页
const goHome = () => {
  router.push('/home')
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''
  
  const date = new Date(time)
  const now = new Date()
  const diff = now - date
  
  // 1分钟内
  if (diff < 60000) {
    return '刚刚'
  }
  
  // 1小时内
  if (diff < 3600000) {
    return `${Math.floor(diff / 60000)}分钟前`
  }
  
  // 今天
  if (date.toDateString() === now.toDateString()) {
    return `今天 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
  }
  
  // 昨天
  const yesterday = new Date(now)
  yesterday.setDate(yesterday.getDate() - 1)
  if (date.toDateString() === yesterday.toDateString()) {
    return `昨天 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
  }
  
  // 其他
  return `${date.getMonth() + 1}月${date.getDate()}日 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
}

// 页面加载时获取通知列表
onMounted(() => {
  loadNotifications()
  updateUnreadCount()
})
</script>

<style scoped>
.notification-center {
  min-height: 100vh;
  background: linear-gradient(135deg, #ffeef8 0%, #fff5f7 100%);
  padding-bottom: 20px;
}

/* 顶部标题栏 */
.page-header {
  position: sticky;
  top: 0;
  z-index: 100;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  background: linear-gradient(135deg, #ff85c0 0%, #ff69b4 100%);
  box-shadow: 0 2px 8px rgba(255, 105, 180, 0.2);
}

.page-header h1 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: white;
  flex: 1;
  text-align: center;
}

.back-btn {
  background: rgba(255, 255, 255, 0.3);
  border: none;
  color: white;
  width: 36px;
  height: 36px;
}

.back-btn:hover {
  background: rgba(255, 255, 255, 0.5);
}

.placeholder {
  width: 36px;
}

/* 未读提示 */
.unread-tip {
  background: linear-gradient(135deg, #fff5f7 0%, #fff8f0 100%);
  border: 1px solid #ffcdd2;
  border-radius: 12px;
  padding: 12px 16px;
  margin: 16px;
  display: flex;
  align-items: center;
  gap: 8px;
  color: #ff6b9d;
  font-size: 14px;
}

.unread-tip .count {
  font-weight: bold;
  font-size: 16px;
}

/* 操作按钮区 */
.action-bar {
  display: flex;
  gap: 8px;
  padding: 0 16px 16px;
  flex-wrap: wrap;
}

.action-btn {
  flex: 1;
  min-width: 0;
  height: 40px;
  font-size: 14px;
  border-radius: 20px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.action-btn:active {
  transform: scale(0.95);
}

/* 批量模式按钮 */
.cancel-btn {
  flex: 1;
  background: linear-gradient(135deg, #f5f5f5 0%, #e8e8e8 100%);
  border-color: #d9d9d9;
  color: #666;
}

.confirm-btn {
  flex: 2;
  background: linear-gradient(135deg, #52c41a 0%, #73d13d 100%);
  border: none;
  color: white;
}

.confirm-btn:hover {
  background: linear-gradient(135deg, #73d13d 0%, #52c41a 100%);
}

.confirm-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

/* 通知列表 */
.notification-list {
  min-height: 400px;
  padding: 0 16px;
}

.notification-item {
  position: relative;
  background: white;
  border-radius: 16px;
  padding: 16px;
  margin-bottom: 12px;
  display: flex;
  align-items: flex-start;
  gap: 12px;
  cursor: pointer;
  transition: all 0.3s;
  border: 2px solid transparent;
}

.notification-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(255, 107, 157, 0.15);
  border-color: #ff6b9d;
}

.notification-item:active {
  transform: scale(0.98);
}

.notification-item.unread {
  background: linear-gradient(135deg, #fff5f7 0%, #fff8f0 100%);
  border-color: #ffcdd2;
}

/* 批量选择模式 */
.notification-item.batch-mode {
  cursor: pointer;
}

.notification-item.batch-mode:hover {
  transform: scale(1.01);
}

.notification-item.batch-mode {
  border: 2px dashed #ffb3d9;
  transition: all 0.3s ease;
}

.notification-item.batch-mode:hover {
  border-color: #ff69b4;
  background: linear-gradient(135deg, #fff 0%, #fff5fb 100%);
}

/* 选中状态 */
.notification-item.selected {
  transform: scale(0.99);
}

.notification-item.selected {
  border: 2px solid #ff69b4 !important;
  box-shadow: 0 4px 20px rgba(255, 105, 180, 0.4);
  background: linear-gradient(135deg, #fff5fb 0%, #ffeef8 100%) !important;
}

/* 复选框样式 */
.notification-checkbox {
  position: absolute;
  top: 10px;
  left: 10px;
  z-index: 10;
  background: white;
  border-radius: 50%;
  padding: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  animation: checkboxFadeIn 0.3s ease;
}

@keyframes checkboxFadeIn {
  from {
    opacity: 0;
    transform: scale(0.5);
  }
  to {
    opacity: 1;
    transform: scale(1);
  }
}

.notification-checkbox:hover {
  transform: scale(1.1);
  box-shadow: 0 4px 12px rgba(255, 105, 180, 0.3);
}

.notification-item.selected .notification-checkbox {
  background: linear-gradient(135deg, #ff69b4 0%, #ff85c0 100%);
  animation: checkboxPulse 0.3s ease;
}

@keyframes checkboxPulse {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.2);
  }
  100% {
    transform: scale(1);
  }
}

.notification-item.selected .notification-checkbox :deep(.el-checkbox__inner) {
  background-color: white;
  border-color: white;
}

.notification-item.selected .notification-checkbox :deep(.el-checkbox__inner::after) {
  border-color: #ff69b4;
}

.notification-icon {
  flex-shrink: 0;
  width: 48px;
  height: 48px;
  border-radius: 50%;
  background: linear-gradient(135deg, #fff5f7 0%, #fff8f0 100%);
  display: flex;
  align-items: center;
  justify-content: center;
}

.notification-content {
  flex: 1;
  min-width: 0;
}

.notification-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 8px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.notification-text {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
  line-height: 1.5;
}

.notification-time {
  font-size: 12px;
  color: #999;
}

.notification-actions {
  flex-shrink: 0;
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.notification-actions .el-button {
  font-size: 13px;
  padding: 4px 12px;
  height: auto;
}

.pagination {
  margin: 20px 16px;
  display: flex;
  justify-content: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header h1 {
    font-size: 18px;
  }

  .action-bar {
    gap: 6px;
  }

  .action-btn {
    font-size: 13px;
    height: 36px;
    padding: 0 12px;
  }

  .notification-item {
    padding: 12px;
    gap: 10px;
  }

  .notification-icon {
    width: 40px;
    height: 40px;
  }

  .notification-icon :deep(.el-icon) {
    font-size: 20px;
  }

  .notification-title {
    font-size: 15px;
  }

  .notification-text {
    font-size: 13px;
  }

  .notification-actions {
    width: 100%;
    justify-content: flex-end;
  }

  .notification-actions .el-button {
    font-size: 12px;
    padding: 4px 10px;
  }

  /* 分页器移动端优化 */
  :deep(.el-pagination) {
    justify-content: center;
  }

  :deep(.el-pagination .el-pager li) {
    min-width: 28px;
    height: 28px;
    line-height: 28px;
    font-size: 13px;
  }

  :deep(.el-pagination button) {
    padding: 0 8px;
    font-size: 13px;
  }
}

/* 平板及以上 */
@media (min-width: 768px) {
  .notification-center {
    padding-bottom: 40px;
  }

  .notification-list {
    max-width: 800px;
    margin: 0 auto;
    padding: 0 24px;
  }

  .unread-tip {
    max-width: 800px;
    margin: 24px auto;
  }

  .action-bar {
    max-width: 800px;
    margin: 0 auto 24px;
    padding: 0 24px;
  }

  .action-btn {
    max-width: 200px;
  }
}
</style>

